//
//  ProfilePageController.m
//  YRSideViewController
//
//  Created by xiabin on 15/1/18.
//  Copyright (c) 2015年 YueRuo. All rights reserved.
//
#import <AssetsLibrary/AssetsLibrary.h>
#import "ProfilePageController.h"
#import "UMNetworkManager.h"
#import "UIViewController+HUD.h"
#import "Utils.h"
#import "UIImageView+WebCache.h"
#import "RETableViewOptionsController.h"
#import "AppDelegate.h"
#import "ImageEditorController.h"
#import "UIImage+Rotation.h"
#import "UserModel.h"
#import "QGUIBasic.h"


#define headpading  10

@interface ProfilePageController ()
{
    UIImagePickerController *imgPicker;
    NSArray *cities, *areas, *userInterests;
    NSMutableArray* opch;
    int curSex;
    int curcel;
    int curimageindex;
    int _fetchavataid;
    int _fetchselfjobid;
    int _updateInterestid;
    int needChangeHead;
    int _updateinfojid;
    int _updateInterestinfoJobid;
    int _uploadimagejid;
    int cityid;
    int reginid;
    int provinceid;
}

@property (strong, readwrite, nonatomic) RETableViewManager *manager;
@property (strong, readwrite, nonatomic) RETableViewSection *headSection;
@property (strong, readwrite, nonatomic) RETextItem *nickItem;
@property (strong, readwrite, nonatomic) RECustomItem *headItem;
@property (strong, readwrite, nonatomic) UIImageView *headBtn;
@property (strong, readwrite, nonatomic) UITableView *tableView;
@end

@implementation ProfilePageController

#pragma mark life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self layoutSubviews];
    //_fetchselfjobid = [[UMNetworkManager sharedInstance] QuerySelfInfoWithCallback:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated {

}

-(void)viewWillAppear:(BOOL)animated {
    [self InitNavItem];
}

#pragma mark ui ctrl delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"用户点击的是第%ld个按钮",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:
            //照一张
        {
            imgPicker=[[UIImagePickerController alloc]init];
            [imgPicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            [imgPicker setDelegate:self];
            [imgPicker setAllowsEditing:NO];
            [MobClick event:@"AddPicCamera"];
            [self.navigationController presentViewController:imgPicker animated:YES completion:^{
            }];
        }
            break;
        case 1:
            //搞一张
        {
            imgPicker=[[UIImagePickerController alloc]init];
            [imgPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [imgPicker setDelegate:self];
            [imgPicker setAllowsEditing:NO];
            [MobClick event:@"AddPicPhoto"];
            [self.navigationController presentViewController:imgPicker animated:YES completion:^{
            }];
            break;
        }
        default:
            break;
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
    
    ImageEditorController* imageEditor = [[ImageEditorController alloc] initWithIMG:image];
    imageEditor.callback = self;
    
    //if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        imageEditor.iscamera = true;
        [picker dismissViewControllerAnimated:YES completion: ^(void) {
            [self.navigationController pushViewController:imageEditor animated:YES];
        }];
    /*} else {
        imageEditor.iscamera = false;
        [picker dismissViewControllerAnimated:YES completion: ^(void) {
            UINavigationController *rootNav = [(AppDelegate*)[[UIApplication sharedApplication]delegate] rootNavController];
            [rootNav pushViewController:imageEditor animated:YES];
        }];
        //[picker pushViewController:imageEditor animated:YES];
    }*/
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

-(void) exitPage {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark custom delegate
-(void) UMAsyncJobDone:(UMJobStatus)emJobStatus JobCookie:(int)JobID And:(id)JobRet
{
    if (emJobStatus == FAILED)
    {
        [self hideHud];
        if (JobID == _updateinfojid) {
            [Utils TTAlertNoTitle:@"更新资料失败!"];
        }
        return;
    }
    if (JobID == _updateinfojid) {
        [self performSelector:@selector(exitPage) withObject:nil afterDelay:1.5f];

    } else if (JobID == 9999) {
        UIImage * userHeadImage = JobRet;
        CATransition *trans=[CATransition animation];
        [trans setDuration:0.25f];
        [trans setType:@"flip"];
        [trans setSubtype:kCATransitionFromLeft];
        [self.headBtn.layer addAnimation:trans forKey:nil];
        [self.headBtn setImage:userHeadImage];
        NSData *image = UIImageJPEGRepresentation(userHeadImage, 0.2);
        _uploadimagejid = [QGNetworkManager UpdateHead:image Callback:self];
        
    } else if (JobID == _uploadimagejid) {
        //[self hideHud];
        NSDictionary* obj = JobRet;
        if ([Utils Dictionary:obj ContainsNormalKey:kUserAvatarUrl]) {

        }
    }
    
}

#pragma mark event response
-(void) popBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) finishEditing
{
    /*int sex = 2;
    if ([_sexItem.value[0] compare:@"男"] == NSOrderedSame) {
        sex = 1;
    }*/
    
    NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] init];
    //[tmpDic setObject:[NSNumber numberWithInt:_source.uid] forKey:kUserUID];
    [tmpDic setObject:_nickItem.value forKey:kUserNick];
    //[tmpDic setObject:[NSNumber numberWithInt:sex] forKey:kUserGender];
    /*if (_ageItem.strvalue.length > 0) {
        [tmpDic setObject:_ageItem.strvalue forKey:kUserBirthday];
    }
    if (_companyItem.value.length>0) {
        [tmpDic setObject:_companyItem.value forKey:kUserCompany];
    }
    if ( [self getStep:0 ChooseID:self.locItem.value InArray:_provinces] ) {
        [tmpDic setObject:[NSNumber numberWithInt:cityid] forKey:kAddressCityID];
        [tmpDic setObject:[NSNumber numberWithInt:reginid] forKey:kAddressRegionId];
        [tmpDic setObject:[NSNumber numberWithInt:provinceid] forKey:kAddressProvinceId];
    }
    if (_qmItem.value.length>0) {
        [tmpDic setObject:_qmItem.value forKey:kUserSig];
    }*/
    
    _updateinfojid = [QGNetworkManager UpdateUserInfo:tmpDic Callback:self];
    [self showHudInView:self.view hint:@"正在上传资料..."];

}

- (void) EditHead:(UITapGestureRecognizer*)sender
{
    UIActionSheet *as= [[UIActionSheet alloc]initWithTitle:@"上传头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"马上照一张" otherButtonTitles:@"从相册中选取", nil ];
    [as showInView:self.view];
}

#pragma mark private methods

- (UIView *)InitFooterview
{
    int btnwidht = self.tableView.frame.size.width;
    int btnheight = 300;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, btnwidht, btnheight+30)];
    headerView.backgroundColor = [UIColor whiteColor];
    return headerView;
}

- (RETableViewSection *)addBasicControls
{
    //__typeof (&*self) __weak weakSelf = self;
    
    self.headItem = [RECustomItem itemWithTitle:@"头像" View:self.headBtn];
    self.headItem.cellHeight = 100+20;
    [_headSection addItem:self.headItem];
    
    //RETableViewSection *section = [RETableViewSection sectionWithHeaderTitle:@" "];
    //[self.manager addSection:section];
    self.nickItem = [RETextItem itemWithTitle:@"昵称" value:nil placeholder:@"点击输入昵称"];
    [_headSection addItem:self.nickItem];
    self.nickItem.textAlignment = NSTextAlignmentRight;
    self.nickItem.charactersLimit = 10;
    self.nickItem.valueTextColor = QGTextBlackL1;
    
    return nil;
}

- (void) InitNavItem {
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_SIZE_WIDTH, 20)];
    statusBarView.backgroundColor=QGNavBG;
    [self.view addSubview:statusBarView];
    
    UIButton* cancelBtn = [Utils NavButtonStyleNormalBLeft:YES NormalImg:@"back" AndHightLight:@"back"];
    [cancelBtn addTarget:self action:@selector(popBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    self.navigationItem.title = @"个人资料";
    
    UIButton *DoneButton = [[UIButton alloc] initWithFrame: CGRectMake(0, 20, 50.0f, 0.0f)];
     DoneButton.backgroundColor = [UIColor redColor];
     [DoneButton setTitle:@"完成" forState:UIControlStateNormal];
     [DoneButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -30)];
     [DoneButton setTitleColor: QGTextWhite forState:UIControlStateNormal];
     [DoneButton setTitleColor: QGTextGrayL1 forState:UIControlStateHighlighted];
     [DoneButton addTarget:self action:@selector(finishEditing) forControlEvents:UIControlEventTouchUpInside];
     DoneButton.titleLabel.font = [UIFont systemFontOfSize: [Utils phoneFontL4]];
     UIBarButtonItem *DoneButtonItem = [[UIBarButtonItem alloc] initWithCustomView:DoneButton];
     self.navigationItem.rightBarButtonItem = DoneButtonItem;
}

-(void) layoutSubviews {
    __weak __typeof(&*self)weakSelf = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.view.mas_top);
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.height.mas_equalTo(weakSelf.view.mas_height);
        make.width.mas_equalTo(weakSelf.view.mas_width);
    }];
}

#pragma mark getter and setter
- (RETableViewSection *)headControls
{
    RETableViewSection *headsession = [RETableViewSection section];
    [self.manager addSection:headsession];
    return headsession;
}

- (UIImageView*) headBtn
{
    if (_headBtn == nil) {
        int headsize = 100;
        _headBtn = [[UIImageView alloc] initWithFrame:CGRectMake(self.tableView.frame.size.width - headsize - 10, headpading, headsize, headsize)];
        [_headBtn sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"headdefault"]];
        [_headBtn setUserInteractionEnabled:YES];
        UITapGestureRecognizer*tapRecognizerleft=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(EditHead:)];
        [_headBtn addGestureRecognizer:tapRecognizerleft];
        _headBtn.layer.cornerRadius = headsize / 2;
        [_headBtn setContentMode:UIViewContentModeScaleAspectFill];
        [_headBtn setClipsToBounds:YES];
        _headBtn.layer.borderWidth = 1;
        _headBtn.layer.borderColor = QGTextGrayL1.CGColor;
    }
    return _headBtn;
}

-(UITableView*) tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] init];
        _tableView.tableFooterView = [UIView new];
        _tableView.scrollEnabled = NO;
        self.manager = [[RETableViewManager alloc] initWithTableView:self.tableView delegate:nil];
        self.headSection = [self headControls];
        [self addBasicControls];
    }
    return _tableView;
}

@end
